const BASE_URL = 'https://i.huhuiyu.top'
const TOKEN_KEY = BASE_URL + '_token'

const TokenInfo = {
	save: (data) => {
		if (data && data.token) {
			uni.setStorageSync(TOKEN_KEY, data.token)
		}
	},
	load: () => {
		let token = uni.getStorageSync(TOKEN_KEY)
		return token ? token : ""
	},
	clear: () => {
		uni.removeStorageSync(TOKEN_KEY)
	}
}
const Api = {

	formatDate: (date, format = 'yyyy-MM-dd hh:mm:ss') => {
		let info = date;
		//如果是时间戳,就转换为日期对象
		if (typeof date === 'number') {
			info = new Date(date);
			info.setTime(date);
		}
		//格式化日期为字符串
		let year = info.getFullYear();
		let month = info.getMonth() + 1;
		let day = info.getDate();
		let hour = info.getHours();
		let minute = info.getMinutes();
		let second = info.getSeconds();
		let result = format.replace('yyyy', year);
		result = result.replace('MM', month < 10 ? '0' + month : month);
		result = result.replace('dd', day < 10 ? '0' + day : day);
		result = result.replace('hh', hour < 10 ? '0' + hour : hour);
		result = result.replace('mm', minute < 10 ? '0' + minute : minute);
		result = result.replace('ss', second < 10 ? '0' + second : second);
		return result;
	},



	userlogo: (uid) => {
		return BASE_URL + '/user/info/logo/' + uid
	},

	send: (url, params, method, cb) => {
		let contentType = 'application/json'
		if (method == 'GET') {
			contentType = 'application/x-www-form-urlencoded'
		}
		uni.request({
			url: BASE_URL + url,
			data: params,
			method: method,
			header: {
				'Authorization': TokenInfo.load(),
				'Content-Type': contentType
			},
			success: (resp) => {
				console.log('请求api成功：', resp)
				TokenInfo.save(resp.data)
				cb(resp.data)
			},
			fail: (err) => {
				console.log('请求api失败：', err)
				cb({
					message: '出bug了',
					success: false,
					code: 500
				})
			}
		})
	},

	get: (url, params, cb) => {
		Api.send(url, params, 'GET', cb)
	},
	post: (url, params, cb) => {
		Api.send(url, params, 'POST', cb)
	},
	put: (url, params, cb) => {
		Api.send(url, params, 'PUT', cb)
	},
	delete: (url, params, cb) => {
		Api.send(url, params, 'DELETE', cb)
	},
	patch: (url, params, cb) => {
		Api.send(url, params, 'PATCH', cb)
	}

}
export {
	Api,
	TokenInfo
}